<template>
  <el-upload ref="uploadEl" v-model:file-list="fileList" :action="baseURL + props.action" :headers="headers" v-bind="$attrs">
    <template #trigger>
      <slot name="trigger">
        <el-button type="primary">选择文件</el-button>
      </slot>
    </template>

    <slot></slot>

    <template #tip>
      <slot name="tip"></slot>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { cache } from '@/utils'
  import { type UploadInstance } from 'element-plus'

  interface IProps {
    action?: string
  }

  const baseURL = window.SITE_CONFIG.apiURL ? window.SITE_CONFIG.apiURL : import.meta.env.VITE_BASE_URL

  const headers = {
    token: cache.getToken()
  }

  const props = withDefaults(defineProps<IProps>(), {
    action: ''
  })

  const uploadEl = ref<UploadInstance>()

  const fileList = defineModel({ default: [] })

  const clearFiles = () => uploadEl.value?.clearFiles()

  const setFiles = (files: any) => uploadEl.value?.handleStart(files)

  /**----------------------------methods----------------------------------------------------------------------- */

  const handleSubmit = () => {
    uploadEl.value?.submit()
  }

  /**----------------------------lifecycle----------------------------------------------------------------------- */

  defineExpose({
    handleSubmit,
    clearFiles,
    setFiles
  })
</script>

<style scoped></style>
